﻿Imports ESRI.ArcGIS.Geometry
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Display
Imports System.IO
Imports System.Xml
Imports System.Data.Odbc
Imports System.Data.SqlClient
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.DataSourcesFile
Imports ESRI.ArcGIS.Catalog
Imports System.ComponentModel

Public Class SiteNouv
    Dim siteDAO As SiteDAO = New SiteDAO
    Dim WidthEcr As String = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width.ToString()
    Dim HeightEcr As String = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height.ToString()
    Dim conn As SqlConnection = Nothing
    Dim cmd As SqlCommand = Nothing
    Private lastGeometry As IElement = Nothing
    Dim effectifConfigLayers As List(Of LayersSiteConfig) = Nothing
    Dim siteAppelations As BindingList(Of SiteAppelation)
    Private Sub SiteNouv_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        tab()
        loadDelimitationLayers()
        siteAppelations = New BindingList(Of SiteAppelation)
        siteAppelationsGrid.DataSource = siteAppelations
    End Sub

    Private Sub tab()
        Me.GroupBoxSite.TabIndex = 1
        Me.siteNameTxt.TabIndex = 1
        Me.siteCodeTxt.TabIndex = 2

        Me.TabControl1.TabIndex = 4
        Me.TabPage1.TabIndex = 4

        Me.TextBoxLatMinD.TabIndex = 4
        Me.TextBoxLatMinM.TabIndex = 5
        Me.TextBoxLatMinS.TabIndex = 6

        Me.TextBoxLatMaxD.TabIndex = 7
        Me.TextBoxLatMaxM.TabIndex = 8
        Me.TextBoxLatMaxS.TabIndex = 9

        Me.TextBoxLatMoyD.TabIndex = 10
        Me.TextBoxLatMoyM.TabIndex = 11
        Me.TextBoxLatMoyS.TabIndex = 12

        Me.TextBoxLonMinD.TabIndex = 13
        Me.TextBoxLonMinM.TabIndex = 14
        Me.TextBoxLonMinS.TabIndex = 15

        Me.TextBoxLonMaxD.TabIndex = 16
        Me.TextBoxLonMaxM.TabIndex = 17
        Me.TextBoxLonMaxS.TabIndex = 18



        Me.TextBoxLonMoyD.TabIndex = 19
        Me.TextBoxLonMoyM.TabIndex = 20
        Me.TextBoxLonMoyS.TabIndex = 21

        Me.TextBoxAlMinD.TabIndex = 22
        Me.TextBoxAlMaxD.TabIndex = 23
        Me.TextBoxAlMoyD.TabIndex = 24


        ' Me.surfaceBox.TabIndex = 25
        'Me.ComboBoxReg.TabIndex = 26
        Me.siteNotesTxt.TabIndex = 28
        Me.siteDelimitTxt.TabIndex = 29

    End Sub

    Private Sub mapDelimitation_OnMouseMove(ByVal sender As System.Object, ByVal e As ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseMoveEvent) Handles mapDelimitation.OnMouseMove
        coordTxt.Text = String.Format("{0}   /  {1}    {2}", e.mapX.ToString("#######.##"), e.mapY.ToString("#######.##"), mapDelimitation.MapUnits.ToString().Substring(4))
    End Sub

    Private Sub enableDrawingStatus_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enableDrawingStatus.CheckedChanged

        If enableDrawingStatus.Checked Then
            AddHandler mapDelimitation.OnMouseDown, AddressOf drawDelimitationOnMap
        Else
            If lastGeometry IsNot Nothing Then
                Dim pGraCont As IGraphicsContainer = mapDelimitation.ActiveView
                pGraCont.DeleteElement(lastGeometry)
                lastGeometry = Nothing
                mapDelimitation.ActiveView.Refresh()
            End If
            RemoveHandler mapDelimitation.OnMouseDown, AddressOf drawDelimitationOnMap
        End If
    End Sub

    Private Sub drawDelimitationOnMap(ByVal sender As Object, ByVal e As ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent)
        'Dim pMXDoc As IMxDocument

        Dim pPoly As IPolygon
        Dim pGraCont As IGraphicsContainer

        Dim pRubberPoly As IRubberBand
        Dim pElem As IElement = Nothing

        ' QI for the IGraphicsContainerSelect interface on the document's activeview
        pGraCont = mapDelimitation.ActiveView

        ' Create a new RubberPolygon
        pRubberPoly = New RubberRectangularPolygon

        'Check which mouse button was pressed...

        ' If button = 1 Then ' If button 1 (left) then create a new polygon (TrackNew)

        ' Return a new Polygon from the tracker object using TrackNew
        pPoly = pRubberPoly.TrackNew(mapDelimitation.ActiveView.ScreenDisplay, Nothing)

        If Not pPoly Is Nothing Then
            ' Create a new PolygonElement and set its Geometry
            pElem = New PolygonElement
            pElem.Geometry = pPoly
            lastGeometry = pElem
            updateGeometryData()

            'Add the new element at Z order zero
            pGraCont.AddElement(pElem, 0)
        End If

        ' Refresh the activeview
        mapDelimitation.ActiveView.Refresh()
        RemoveHandler mapDelimitation.OnMouseDown, AddressOf drawDelimitationOnMap

    End Sub

    Private Sub mapDelimitation_OnMouseUp(ByVal sender As System.Object, ByVal e As ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseUpEvent) Handles mapDelimitation.OnMouseUp
        updateGeometryData()
    End Sub

    Private Sub updateGeometryData()
        If lastGeometry IsNot Nothing Then

            'Dim curve As ICurve = lastGeometry.Geometry
            'peremitreBox.Text = curve.Length

            'Dim area As IArea = lastGeometry.Geometry
            'surfaceBox.Text = area.Area


            xmax.Text = lastGeometry.Geometry.Envelope.XMax
            ymax.Text = lastGeometry.Geometry.Envelope.YMax
            xmin.Text = lastGeometry.Geometry.Envelope.XMin
            ymin.Text = lastGeometry.Geometry.Envelope.YMin
            xmoy.Text = (lastGeometry.Geometry.Envelope.XMax + lastGeometry.Geometry.Envelope.XMin) / 2
            ymoy.Text = (lastGeometry.Geometry.Envelope.YMax + lastGeometry.Geometry.Envelope.YMin) / 2
        End If
    End Sub

    Private Sub addSite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addSite.Click

        If siteNameTxt.Text Is Nothing OrElse siteNameTxt.Text.Trim() = "" Then
            MsgBox("Le nom du site est obligratoire !!", MsgBoxStyle.Critical, "Erreur de saisie")
            Exit Sub
        End If

        If siteCodeTxt.Text Is Nothing OrElse siteCodeTxt.Text.Trim() = "" Then
            MsgBox("Le code du site est obligratoire !!", MsgBoxStyle.Critical, "Erreur de saisie")
            Exit Sub
        End If
        'check for stokage File
        If isFileNameValid(siteCodeTxt.Text) Then
            If isDatabaseExist(siteCodeTxt.Text) Then
                MsgBox("Le site " & siteCodeTxt.Text & " existe déja", MsgBoxStyle.Exclamation, "Attention")
                Exit Sub
            End If

            createSiteDatabase(siteCodeTxt.Text)
            copySiteLayers(siteCodeTxt.Text)
            createSiteDatas(siteCodeTxt.Text, siteNameTxt.Text)
            Dim site As Site = New Site()
            site.CODSITE = siteCodeTxt.Text
            site.NOMSITE = siteNameTxt.Text
            site.LATN_SIT = xmin.Text
            site.LATS_SIT = xmax.Text
            site.LONE_SIT = ymin.Text
            site.LONW_SIT = ymax.Text
            site.DELIM_SIT = siteDelimitTxt.Text
            site.NOTES_SIT = siteNotesTxt.Text
            site = siteDAO.addSite(site)
            addDelimitationCoordToLayer(siteCodeTxt.Text)
            Try
                siteDAO.addSiteAppelations(site, siteAppelations)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
            Me.Hide()
        Else
            MsgBox("Le nom du site n'est pas valide !!")
            Exit Sub
        End If
    End Sub
    Public Sub addSigCol(ByVal featureLayer As IFeatureLayer, ByVal tableName As String, ByVal dbConnexion As String)
        If featureLayer Is Nothing Then
            Return
        End If

        If tableName Is Nothing OrElse String.IsNullOrEmpty(tableName.Trim) Then
            Return
        End If
        If isColExistInTable(SILMProperties.SIG_COL_NAME, featureLayer.Name, dbConnexion) Then
            Return
        End If
        Dim con As SqlConnection = New SqlConnection(dbConnexion)
        Try
            con.Open()
            ' For Each layerName As String In layersMap.Keys()

            Dim query As String = "ALTER TABLE " & _
            tableName & _
            " ADD " & _
            SILMProperties.SIG_COL_NAME & " " & _
            "VARCHAR(20) DEFAULT null"
            Dim cmd As SqlCommand = New SqlCommand(query, con)
            cmd.ExecuteNonQuery()

            con.Close()
        Catch ex As Exception

        End Try
        If featureLayer Is Nothing Then
            Return
        End If
        AddFieldToFeatureClass(featureLayer.FeatureClass, createField(SILMProperties.SIG_COL_NAME, "Identifiant GIS", esriFieldType.esriFieldTypeString))
    End Sub
    Public Function isDatabaseExist(ByVal databaseName As String) As Boolean
        'conStr = "Data Source=" + txtServerName.Text + ";Initial Catalog=" + txtDatabaseName.Text + ";User Id=" + txtUserName.Text + ";Password=" + pbPassword.Text + ""
        Dim ConnectionString As String = getSiteDatabaseString(databaseName)
        Dim con As SqlConnection = New SqlConnection(ConnectionString)
        Try
            con.Open()
            con.Close()
            Return True
            MessageBox.Show("Connexion réussie !!")

        Catch ex As Exception
            Return False
        End Try
        Return False
    End Function

    Public Function isFileNameValid(ByVal name As String) As Boolean
        Dim isValid As Boolean = True
        If name Is Nothing OrElse name.Trim() = String.Empty Then
            isValid = False
            Return False
        End If
        isValid = IsValidFileNameOrPath(name)
        Return isValid
    End Function

    Function IsValidFileNameOrPath(ByVal name As String) As Boolean
        ' Determines if the name is Nothing.
        If name Is Nothing Then
            Return False
        End If

        ' Determines if there are bad characters in the name.
        For Each badChar As Char In System.IO.Path.GetInvalidFileNameChars
            If InStr(name, badChar) > 0 Then
                Return False
            End If
        Next

        ' The name passes basic validation.
        Return True
    End Function

    Public Function checkPathToInstall(ByVal path As String) As Boolean

        If path <> String.Empty Then
            If Not Directory.Exists(path) Then
                MsgBox("Le repertoire de stokage n'est pas bin configuré !!")
                Return False
            End If
        Else
            MsgBox("Vous devez selectionner un nom valide !!")
            Return False
        End If
        Return True
    End Function

    Public Sub createSiteDatas(ByVal codeSite As String, ByVal siteName As String)

        Dim siteXmlPath As String = getSiteXmlFilePath(codeSite)
        Dim m_mapDocumentName As String = getSiteMapDocumentFilePath(codeSite)
        Dim configPath As String = getSiteConfigFilePath(codeSite)
        setEffectiveLayers()
        Dim mapDocument As IMapDocument = New MapDocument()
        mapDocument.New(m_mapDocumentName)

        Dim imap As IMap = mapDocument.Map(0)
        Dim layersDocFiles As String = getSiteLayersPath(codeSite)
        For Each LayerConfig As LayersSiteConfig In effectifConfigLayers
            Dim pWorkspaceFactory As IWorkspaceFactory = New ShapefileWorkspaceFactory
            Dim pFeatureWorkspace As IFeatureWorkspace = pWorkspaceFactory.OpenFromFile(layersDocFiles, 0)
            Dim pathLayer As String = layersDocFiles & "\" & LayerConfig.layerName
            Dim pFeatureLayer As IFeatureLayer = New FeatureLayer()
            pFeatureLayer.FeatureClass = pFeatureWorkspace.OpenFeatureClass(LayerConfig.layerName)
            pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName
            imap.AddLayer(pFeatureLayer)
            addSigCol(pFeatureLayer, LayerConfig.layerTable, getSiteDatabaseString(codeSite))
        Next

        mapDocument.Save(True, True)
        'imap.AddLayer()
        mapDocument.Close()

        Dim XmlDoc As XmlDocument = New XmlDocument()
        Dim root As XmlElement = XmlDoc.CreateElement("Workspace")
        Dim wsCodeAttribute As XmlAttribute = XmlDoc.CreateAttribute("Code")
        wsCodeAttribute.InnerText = codeSite
        root.Attributes().Append(wsCodeAttribute)

        Dim wsNameAttribute As XmlAttribute = XmlDoc.CreateAttribute("Name")
        wsNameAttribute.InnerText = siteName
        root.Attributes().Append(wsNameAttribute)

        Dim mxdNode As XmlElement = XmlDoc.CreateElement("mxdFile")
        mxdNode.InnerText = m_mapDocumentName
        root.AppendChild(mxdNode)

        Dim configNode As XmlElement = XmlDoc.CreateElement("configFile")
        configNode.InnerText = siteXmlPath
        root.AppendChild(configNode)

        XmlDoc.AppendChild(root)
        XmlDoc.Save(configPath)

        saveXML(codeSite)

    End Sub
    Private Function CreatePoint(ByVal x As Double, ByVal y As Double) As IPoint
        ' create a new point instance and initialize its coordinates
        Dim point As IPoint = New PointClass()
        point.PutCoords(x, y)
        Return point
    End Function
    Public Sub addDelimitationCoordToLayer(ByVal codeSite As String)
        Try
            If IsNumeric(xmin.Text) And IsNumeric(xmax.Text) And IsNumeric(ymin.Text) And IsNumeric(ymax.Text) Then
                Dim layersDocFiles As String = getSiteLayersPath(codeSite)
                Dim pWorkspaceFactory As IWorkspaceFactory = New ShapefileWorkspaceFactory
                Dim pFeatureWorkspace As IFeatureWorkspace = pWorkspaceFactory.OpenFromFile(layersDocFiles, 0)
                Dim featureCls As IFeatureClass = pFeatureWorkspace.OpenFeatureClass(SILMProperties.DELIM_LAYER_NAME)
                Dim feature As IFeature = featureCls.CreateFeature()
                Dim poly As Polygon = New Polygon
                feature.Shape = lastGeometry.Geometry
                feature.Store()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Public Sub setEffectiveLayers()
        If effectifConfigLayers Is Nothing Then
            effectifConfigLayers = New List(Of LayersSiteConfig)
            Dim layersConf As List(Of LayersSiteConfig) = siteDAO.getSiteDefaultLayers()
            For Each layerConf As LayersSiteConfig In layersConf
                If layerConf.layerActif Then
                    effectifConfigLayers.Add(layerConf)
                End If
            Next
            Dim delimLayer As LayersSiteConfig = New LayersSiteConfig()
            delimLayer.layerName = SILMProperties.DELIM_LAYER_NAME
            delimLayer.layerActif = True
            delimLayer.layerLabel = NameWithoutExtention(SILMProperties.DELIM_LAYER_NAME)
            effectifConfigLayers.Add(delimLayer)
        End If
    End Sub
    Public Sub copySiteLayers(ByVal codeSite As String)

        Dim layersDocFiles As String = getSiteLayersPath(codeSite)
        Dim defaultSitesLayersPath As String = getSiteDefaultLayerPath()
        Dim configSitesLayersPath As String = getWorkSpaceConfigLayerPath()
        setEffectiveLayers()
        For Each tempLayer As LayersSiteConfig In effectifConfigLayers
            If tempLayer.layerName <> SILMProperties.DELIM_LAYER_NAME Then
                For Each filetdx As String In IO.Directory.GetFiles(configSitesLayersPath, tempLayer.layerLabel & ".*")
                    System.IO.File.Copy(filetdx, layersDocFiles & "\" & NameOnlyFromFullPath(filetdx), True)
                Next
            Else
                For Each filetdx As String In IO.Directory.GetFiles(defaultSitesLayersPath, tempLayer.layerLabel & ".*")
                    System.IO.File.Copy(filetdx, layersDocFiles & "\" & NameOnlyFromFullPath(filetdx), True)
                Next
            End If
        Next
    End Sub

    Private Sub createSiteDatabase(ByVal site As String)
        Try
            If site Is Nothing OrElse site Is Nothing OrElse site.Trim().Length = 0 Then
                Exit Sub
            End If
            Dim codeSite As String = site
            Dim databaseDocFiles As String = getSiteDatabasePath(codeSite)
            Dim siteMdfFile As String = databaseDocFiles & System.IO.Path.DirectorySeparatorChar & codeSite & ".mdf"
            Dim siteLdfFile As String = databaseDocFiles & System.IO.Path.DirectorySeparatorChar & codeSite & ".ldf"
            ' Create a connection
            Dim ConnectionString As String = Settings.Default.ConnectionStr '"Data Source=localhost\sqlexpress;Initial Catalog=silm_11;User Id=sa;Password=sa"
            Dim tokens As String() = ConnectionString.Split(";")
            tokens(1) = "Initial Catalog=Master"
            ConnectionString = tokens(0) & ";" & tokens(1) & ";" & tokens(2) & ";" & tokens(3)
            conn = New SqlConnection(ConnectionString)
            ' Open the connection
            If conn.State <> ConnectionState.Open Then
                conn.Open()
            End If
            ' Dim sql As String = "CREATE DATABASE " & codeSite & " ON PRIMARY " & _
            '"( NAME = N'" & codeSite & "', filename = '" & siteMdfFile & "', size=3," + "maxsize=5, filegrowth=10%)log on"
            ' + "(name=mydbb_log, filename='" & siteMdfFile & "',size=3," + "maxsize=20,filegrowth=1)"
            Dim sql As String = "CREATE DATABASE " & codeSite & " ON  PRIMARY " & _
            " ( NAME = N'" & codeSite & "', FILENAME = N'" & siteMdfFile & "' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) " & _
            " LOG ON " & _
            "( NAME = N'" & codeSite & "_log', FILENAME = N'" & siteLdfFile & "' , SIZE = 2816KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)"
            ExecuteSQLStmt(sql)
            Dim siteSQLPath As String = getSiteSqlPath(codeSite)

            If File.Exists(siteSQLPath) Then
                Dim oRead As System.IO.StreamReader
                oRead = File.OpenText(siteSQLPath)
                Dim SQlTables As String = ""
                SQlTables = "USE [" & codeSite & "] "
                SQlTables = SQlTables & oRead.ReadToEnd()
                ExecuteSQLStmt(SQlTables)
            End If

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Public Sub saveXML(ByVal codeSite As String)
        'Dim siteDirectory As String = getSiteConfigFilePath(codeSite)

        Dim xmlpath As String = getSiteXmlFilePath(codeSite)
        Dim XmlDoc As XmlDocument = New XmlDocument()
        Dim root As XmlElement = XmlDoc.CreateElement("Configuration")

        Dim databaseNode As XmlElement = XmlDoc.CreateElement("Database")
        Dim ConnectionString As String = getSiteDatabaseString(codeSite)

        databaseNode.InnerText = ConnectionString

        Dim layersFolderNode As XmlElement = XmlDoc.CreateElement("Layers")

        layersFolderNode.InnerText = getSiteLayersPath(codeSite)

        root.AppendChild(databaseNode)
        root.AppendChild(layersFolderNode)

        Dim LayersNode As XmlElement = XmlDoc.CreateElement("Mappings")
        root.AppendChild(LayersNode)
        XmlDoc.AppendChild(root)
        XmlDoc.Save(xmlpath)

    End Sub

    Private Sub ExecuteSQLStmt(ByVal sql As String)
        Try
            ' Open the connection
            If conn.State = ConnectionState.Open Then
                conn.Close()
            End If
            Dim ConnectionString As String = Settings.Default.ConnectionStr '"Data Source=localhost\sqlexpress;Initial Catalog=silm_11;User Id=sa;Password=sa"
            Dim tokens As String() = ConnectionString.Split(";")
            tokens(1) = "Initial Catalog=Master"
            ConnectionString = tokens(0) & ";" & tokens(1) & ";" & tokens(2) & ";" & tokens(3)
            conn.ConnectionString = ConnectionString
            conn.Open()
            cmd = New SqlCommand(sql, conn)

            cmd.ExecuteNonQuery()
        Catch ae As SqlException
            MessageBox.Show(ae.Message.ToString())
        End Try
    End Sub

    Private Sub loadDelimitationLayers()
        ' Create a new ShapefileWorkspaceFactory object and
        ' open a shapefile folder - the path works with standard 9.3 installation
        Dim delimitationPath As String = getSiteDelimitationsPath()

        'Dim workspaceFactory As IWorkspaceFactory = New ShapefileWorkspaceFactory()
        'Dim featureWorkspace As IFeatureWorkspace = TryCast(workspaceFactory.OpenFromFile(delimitationPath, 0), IFeatureWorkspace)
        '' Create a new FeatureLayer and assign a shapefile to it
        'Dim featureLayer As IFeatureLayer = New FeatureLayerClass
        'featureLayer.FeatureClass = featureWorkspace.OpenFeatureClass("COMMUNES")
        'Dim layer As ILayer = featureLayer
        'layer.Name = featureLayer.FeatureClass.AliasName
        '' Add the Layer to the focus map
        'Dim pMap As ESRI.ArcGIS.Carto.IMap = mapDelimitation.ActiveView.FocusMap
        'pMap.AddLayer(featureLayer)
        addLayerToMap("COMMUNES", mapDelimitation.ActiveView.FocusMap, delimitationPath)
    End Sub


    Private Sub typeInventBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub appelationBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim siteAppelationForm As SiteApp = New SiteApp()
        siteAppelationForm.ShowDialog(Me)

    End Sub



End Class